<template>
    <div>
        <el-card shadow="hover" style="padding:0" v-show="!dictId">
            <div slot="header" class="margin-top-10">
                <span style="font-weight: bold;">字典选项{{this.dictId}}</span>
            </div>
            <div style="padding-left: 15px;">
                <div style="border:3px solid #ddd; border-top: 0; border-right: 0;border-bottom:0;padding-left: 10px;display:flex;height: 50px;line-height: 50px;">点击字典查看详情</div>
            </div>
        </el-card>
        
        <el-card shadow="hover" style="padding:0" v-show="dictId">
            <!-- 工具栏 -->
            <div class="search-bar margin-top-10">
                <div class="left">
                    <el-form class="searchForm" ref="searchForm" :model="searchForm" :inline="true">
                        <el-form-item prop="searchKey">
                            <el-select
                                style="width: 120px" 
                                no-data-text="暂无数据" placeholder="请选择" v-model="searchForm.searchKey" clearable @clear="handleClearSelect" size="small">
                                <el-option
                                    v-for="item in searchColumns"
                                    :key="item.key"
                                    :label="item.label"
                                    :value="item.key">
                                </el-option>
                            </el-select>
                        </el-form-item>
    
                        <el-form-item prop="searchValue">
                            <el-input style="width: 150px" placeholder="请输入关键字" v-model="searchForm.searchValue" clearable @clear="handleClearKeyword" size="small"></el-input>
                        </el-form-item>

                        <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small" circle></el-button>
                        <el-button type="primary" icon="el-icon-refresh-left" @click="handleResetSearch('searchForm')" size="small" circle></el-button>
                        <el-button type="primary" icon="el-icon-plus" @click="handleOpenDialog('create')" size="small" circle></el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="handleDelete" size="small" circle></el-button>
    
                    </el-form>
                </div>
            </div>

            <!-- 表格 -->
            <el-table
                ref="table" size="small" empty-text="暂无数据" max-height="600"
                element-loading-text="给我一点时间"
                fit stripe border highlight-current-row
                v-loading="loading"
                :data="tableData"
                :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                @selection-change="handleSelection">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" width="55" align="center"></el-table-column>
                
                <el-table-column label="字典标签" align="center" width="150">
                    <template slot-scope="scope">
                        <el-tag type="danger" size="small" v-if="scope.row.selected === 1">{{scope.row.label}}</el-tag>
                        <span v-else>{{scope.row.label}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="字典值" prop="value" show-overflow-tooltip column-key="value" align="center" min-width="150"/>
                <el-table-column label="排序" prop="sort" column-key="sort" align="center" width="80px"/>
                <el-table-column label="状态" width="80px" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" size="small" v-if="scope.row.status === 1">正常</el-tag>
                        <el-tag type="danger" size="small" v-else>禁用</el-tag>
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" width="80px" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="primary" size="small" icon="el-icon-edit" @click="handleOpenDialog('update', scope.row)" circle></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页工具栏 -->
            <div class="pagination">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="searchForm.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="searchForm.rows"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>

            <!-- 窗口 -->
            <el-dialog
                :title="actionTypeMap[actionType]"
                :visible.sync="dialogVisible"
                @close="handleDialogClose">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                    <el-form-item label="字典标签" prop="label">
                        <el-input v-model="form.label" placeholder="字典标签" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="字典值" prop="value">
                        <el-input v-model="form.value" placeholder="字典值" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remarks">
                        <el-input v-model="form.remarks" placeholder="字典值" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="排序" prop="sort">
                                <el-input-number v-model="form.sort" :min="1" :max="10000" placeholder="排序"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="默认值" prop="selected">
                                <el-radio-group v-model="form.selected">
                                    <el-radio :label="1">是</el-radio>
                                    <el-radio :label="0">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="状态" prop="status">
                                <el-radio-group v-model="form.status">
                                    <el-radio :label="1">正常</el-radio>
                                    <el-radio :label="0">禁用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { save, deleted, updated, info, page } from "@/api/admin/sysdictdetail"
import { parseTime } from "@/libs/utils"
import valid from "@/libs/rules"
export default {
    props: {
        dictId: {
            default: 0,
            required: true
        }
    },
    data() {
        return {
            actionType: 'create',
            actionTypeMap: { create: '创建', update: '编辑' },
            dialogVisible: false,
            loading: false,
            submitLoading: false,
            total: 0,
            tableData: [],
            searchForm: {
                page: 1,
                limit: 10,
                searchKey: '',
                searchValue: ''
            },
            searchColumns: [],
            form: {
                id: null,
                dictId: null,
                label: null,
                value: null,
                selected: 0,
                status: 1,
                remarks: null,
                ctime: null,
                utime: null,
            	sort: 99
            },
            rules: {
                name: [valid.required()]
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.setSearchColumnsKey()
        })
    },
    methods: {
        handleOpenDialog(type, row) { // 打开表单窗口
            this.actionType = type
            this.dialogVisible = true
            if (type === 'update') {
                this.getOne(row.id).then(res => {
                    this.form = Object.assign({}, res.data)
                })
            } else {
                this.form.id = null
            }
        },
        handleDialogClose() { //表单窗口关闭
            this.handleReset('form')
        },
        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getTableDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getTableDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getTableDataList()
        },
        handleReset(name) { // 重置表单
            const refs = this.$refs
            refs[name].resetFields()
        },
        setSearchColumnsKey() { // 设置查询条件Key
            this.searchColumns = []
            for (let column of this.$refs.table.columns) {
                if (column.columnKey) {
                    this.searchColumns.push({
                        key: column.columnKey,
                        label: column.label
                    })
                }
            }
        },
        handleClearSelect() { // 清空搜索下拉框
            this.searchForm.searchKey = null
        },
        handleClearKeyword() { // 清空关键字
            this.searchForm.searchValue = null
        },
        handleSearch() { // 单条件搜索
            if (this.searchForm.searchValue.trim()) {
                let searchFormDefault = Object.assign({}, this.searchForm)
                let search = Object.assign({}, this.searchForm)
                this.searchForm[this.searchForm.searchKey] = this.searchForm.searchValue
                this.getTableDataList()
                this.searchForm = searchFormDefault //恢复条件查询默认值
            }
        },
        handleSubmit(name) { // 提交表单
        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    if (this.actionType === 'create') {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                //this.dialogVisible = false
                                //this.handleReset('form')
                                this.getTableDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else if (this.actionType === 'update') {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.dialogVisible = false
                                this.handleReset('form')
                                this.getTableDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },

        handleDelete(row) { // 删除
            let ids = []
            if (row.id != undefined) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {    
            	this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted({ idList: ids }).then(response => {
                        if (this.ResultMessage(response)) {
                            this.getTableDataList()
                        }
                    }).catch(error => {
                        this.$notify({ title: '提示', message: '删除失败', type: 'error', duration: 2000 })
                    })
                }).catch(() => {})
            }
        },

        getOne(id) { // 根据ID加载数据
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                    	this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                	this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },

        getTableDataList() { // 加载列表数据
            this.loading = true
            this.$nextTick(() => {
                this.searchForm.dictId = this.dictId
                this.form.dictId = this.dictId
                if(this.searchForm.dictId) {
                    page(this.searchForm).then(res => {
                        if (this.ResultMessage(res, false)) {
                            this.tableData = res.data.records
                            this.total = res.data.total
                            this.loading = false
                        } else {
                            this.loading = false
                        }
                    }).catch(error => {
                        this.loading = false
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }
            })
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>